import 'package:fish_redux/fish_redux.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:hayll_app_village_master/hayll/network/yll_network.dart';
import 'package:hayll_app_village_master/hayll/village_manager/device/device_register_page/bean/device_vendor_response.dart';
import 'package:hayll_app_village_master/hayll/village_manager/network/village_action.dart';
import 'action.dart';
import 'state.dart';

Effect<DeviceRegisterState> buildEffect() {
  return combineEffects(<Object, Effect<DeviceRegisterState>>{
    DeviceRegisterAction.action: _onAction,
    DeviceRegisterAction.changeDeviceVendor: _changeDeviceVendor,
    DeviceRegisterAction.register: _register,
    Lifecycle.initState: _initData,
  });
}

void _onAction(Action action, Context<DeviceRegisterState> ctx) {}

void _initData(Action action, Context<DeviceRegisterState> ctx) {
  var params = {'pageNum': 1, 'pageSize': 1000};
  YllNetwork.requestPost(VillageAction.getRobbitVenorList, params: params,
      success: (json) {
    //获取结果
    if (json['data'] != null) {
      var deviceVendorResult = DeviceVendorListResult.fromJson(json['data']);
      ctx.state.vendorList.clear();
      if (deviceVendorResult.data != null) {
        ctx.state.vendorList.addAll(deviceVendorResult.data);
        ctx.state.selectedVendorId = deviceVendorResult.data.isNotEmpty
            ? deviceVendorResult.data.first.deviceTypeId
            : -1;
      }
      ctx.dispatch(DeviceRegisterActionCreator.refreshUI());
    }
  }, failed: (errorCode, errorMsg) {
    Fluttertoast.showToast(msg: '$errorCode,$errorMsg');
  });
}

void _changeDeviceVendor(Action action, Context<DeviceRegisterState> ctx) {
  ctx.state.selectedVendorId = action.payload['vendorId'];
  ctx.dispatch(DeviceRegisterActionCreator.refreshUI());
}

void _register(Action action, Context<DeviceRegisterState> ctx) {
  if (ctx.state.nameController.text.isEmpty) {
    Fluttertoast.showToast(msg: '门禁名称不能为空');
  } else if (ctx.state.deviceNoController.text.isEmpty) {
    Fluttertoast.showToast(msg: '设备编号不能为空');
  } else if (ctx.state.selectedVendorId <= 0) {
    Fluttertoast.showToast(msg: '必须选择一个厂商');
  } else {
    var params = {
      'villageId': ctx.state.villageId,
      'location': ctx.state.nameController.text,
      'termId': ctx.state.deviceNoController.text,
      'deviceTypeId': ctx.state.selectedVendorId
    };
    if (ctx.state.unit != null) {
      params['itemId'] = ctx.state.unit.itemId;
      params['switchType'] = 'ITEMDOOR';
      params['buildingItemCode'] =
          '${ctx.state.build.buildingCode}${ctx.state.unit.itemCode}';
    } else {
      params['itemId'] = 0;
      params['switchType'] = 'VILLAGEDOOR';
    }
    YllNetwork.requestPost(VillageAction.addRobbit, params: params,
        success: (json) {
      //获取结果
      Fluttertoast.showToast(msg: '添加成功');
    }, failed: (errorCode, errorMsg) {
      Fluttertoast.showToast(msg: '$errorCode,$errorMsg');
    });
  }
}
